from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from google.appengine.api import users
from models.KhachHang import KhachHang
from utils.Const import TrangThaiGiaBan, LoaiNhanVien
from utils.permission_required import permission_required
from webapp2_extras.appengine.users import login_required
import WSGI
import json as simplejson
import logging
import math
import webapp2

logger = logging.getLogger("GUIQuanLyNhanVien")


class GuiQuanLyKhachHang(webapp2.RequestHandler):
    priv = ''
    perm = 'KinhDoanh.QuanLyKhachHang'
    @permission_required
    def get(self):
        
        cbbTenNV = {}
        if self.priv == 'Owner':
            cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        else:
            user = users.get_current_user()
            nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
            cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, nhanVien.key().id())
        for item in cbbTenNV:
            item['tenNV'] = str(item['id']) + ' - ' + item['tenNV']
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        lstNVGiaoHangText = ''
        for item in cbbTenNV:
            #if item['codeLoaiNV'] == LoaiNhanVien.GIAO_HANG:
            lstNVGiaoHangText += str(item['id']) + ':' + item['tenNV'] + ';'
        if lstNVGiaoHangText != '':
            lstNVGiaoHangText = lstNVGiaoHangText[:-1] 
        
        template_values = {
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'priv': self.priv,                           
                        'cbbTenNV': cbbTenNV,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri),
                        'lstNVGiaoHangText': lstNVGiaoHangText
        }

        template = WSGI.jinja_environment.get_template('/html/QuanLyKhachHang.html')
        self.response.out.write(template.render(template_values))



class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'KinhDoanh.QuanLyKhachHang'
    @permission_required
    def _handleRequest(self):
        funcName = self.request.get('func')
        funcMapping = {'getListKhachHang': 'getListKhachHang',
                       'updateKhachHang': 'updateKhachHang'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    @login_required
    def get(self):
        return self._handleRequest()

    def post(self):
        return self._handleRequest()
    
    def getListKhachHang(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maNV = self.request.get('maNV')
        
        user = users.get_current_user()
        nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
        
        if self.priv != 'Owner':
            if maNV !='':
                nv = DaoQuanLyNhanVien.getNhanVienById(int(maNV))
                if nv.parentId != nhanVien.key().id() and nv.key().id() != nhanVien.key().id():
                    return 1
        
        parentId = nhanVien.key().id()
        
        if nhanVien.codeLoaiNV == LoaiNhanVien.QUAN_LY:
            parentId = ''
        
        rows, rowNum = DaoQuanLyNhanVien.getListKhachHang(maNV, gridRowNum, int((pageNum-1)*gridRowNum), parentId)
        for item in rows:
            if item['maNVGiaoHang'] is not None:
                item['nvGiaoHang'] = str(item['maNVGiaoHang']) + ' - ' + item['tenNVGiaoHang']
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateKhachHang(self):
        maKH = self.request.get('id')
        if maKH != '_empty':
            kh = KhachHang.get_by_id(int(maKH))
            if kh.trangThai == TrangThaiGiaBan.DUYET:
                return 1
        else:
            kh = KhachHang()
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            DaoQuanLyNhanVien.deleteKhachHang(kh)
            return 1
        else:
            kh.tenKhachHang = self.request.get('tenKhachHang')
            kh.nguoiLienHe = self.request.get('nguoiLienHe')
            kh.dienThoai = self.request.get('dienThoai')
            kh.diaChi = self.request.get('diaChi')
            kh.quanHuyen = self.request.get('quanHuyen')
            kh.thanhPho = self.request.get('thanhPho')
            kh.diaChiGiaoHang = self.request.get('diaChiGiaoHang')
            kh.moTaKhachHang = self.request.get('moTaKhachHang')
            kh.loaiHinhKinhDoanh = self.request.get('loaiHinhKinhDoanh')
            kh.quyMo = self.request.get('quyMo')
            kh.ghiChu = self.request.get('ghiChu')
            kh.congNo = 0.0
            if self.request.get('chietKhau') != '':
                kh.chietKhau = float(self.request.get('chietKhau'))
            
            if self.request.get('nvGiaoHang') != '':
                kh.maNVGiaoHang = int(self.request.get('nvGiaoHang'))
                kh.tenNVGiaoHang = DaoQuanLyNhanVien.getNhanVienById(kh.maNVGiaoHang).tenNV
            
            maNV = self.request.get('maNV')
            
            user = users.get_current_user()
            nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
            
            if self.priv == 'Staff':
                maNV = nhanVien.key().id()
                kh.trangThai = TrangThaiGiaBan.CHUA_DUYET
            elif self.priv == 'Owner':
                kh.trangThai = self.request.get('trangThai')
                
                
            if kh.maNV is None:
                if maNV != '':
                    kh.maNV = int(maNV)
                else:
                    kh.maNV = nhanVien.key().id()
            
            DaoQuanLyNhanVien.createOrUpdateKhachHang(kh)
            return 1
        
        
            
        